<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output; 
use think\Db; 
use think\console\input\Argument;
use think\Log;

class Sms extends Command
{
    protected function configure()
    {
        $this->setName('sms')
        ->setDescription('run tp5 cli mode');
        //参数1
        $this->addArgument('now', Argument::REQUIRED, "The now of the class");
    }
    protected function execute(Input $input, Output $output)
    {       
        
    	$now = $input->getArgument('now');   
    	$type = 'test_mobile';
    	$config = Db::name('sms_config')->where('key', $type)->find();
    	$mobiles = explode(',', $config['value']);  
    	
    	if($now == 'birthday'){
    	    self::birthDayNotice($mobiles);
			exit;
    	}
    	
    	if($now == 'passport'){
    	    self::passportNotice($mobiles);
			exit;
    	} 
    }
    
    
    
    /**
     * 生日提醒
     */
    public static function  birthDayNotice($mobiles){ 
    	$type = 'birth_message';
    	$config = Db::name('sms_config')->where('key', $type)->find();
    	if(empty($config)){
    		echo "缺少模版文件";exit;
    	}
    	$the_date = date('Y-m-d');
    	//查询当前日期
    	$month_day = date('m-d'); 
    	//查询用户 
    	$customrers = Db::name('sms_customer')->select(); 
    	//查询节日
    	$festival_info = Db::name('sms_festival')->where('festival_date',  $the_date)->find(); 
    	if(empty($festival_info)){
    	    $festival_msg = "愿友谊地久天长！";
    	}else{
    	    $festival_msg = $festival_info['message'];
    	} 
    	$success_mobile = "";
    	$fail_mobile = ""; 
    	foreach ($customrers as $customrer){
    		$customrer_month_day = date('m-d', strtotime($customrer['birth_date']));
    		if($customrer_month_day == $month_day){
    			$mobile = $customrer['mobile'];
    			$name = $customrer['name']; 
    			$content ="【新天会展】". $config['value'];
    			$params = "$mobile,$name,$festival_msg";   
    			$result = self::sendSingleSms($content, $params);
    			if($result == true){
    			    $success_mobile .= $mobile.",";
    			}else{
    			    $fail_mobile .= $mobile.",";
    			} 
    		}
    	}  
    	//这个给内部人员通知消息用
    	foreach ($mobiles as $mobile){ 
    	    $name = "福小新";
    	    $content ="【新天会展】". $config['value'];
    	    $params = "$mobile,$name,$festival_msg";   
    	    $result = self::sendSingleSms($content, $params);
    	    if($result == true){
    	        $success_mobile .= $mobile.",";
    	    }else{
    	        $fail_mobile .= $mobile.",";
    	    } 
    	}
    	//记录日志
    	$send_result = "生日祝福 成功的手机号有：".$success_mobile."; 失败的手机号有： ".$fail_mobile;
    	$send_time = date('Y-m-d H:i:s');
    	$data = [
    	    'send_result' => $send_result,
    	    'send_time' => $send_time
    	];
    	Db::name('sms_log')->insert($data);
    	
    	echo  date("Y-m-d") ." Today's birthday run is over"; 
    }
    
    /**
     * 护照到期
     */
    public static function  passportNotice($mobiles){
    	$type = 'passport_message';
    	$config = Db::name('sms_config')->where('key',$type)->find();
    	if(empty($config)){
    		echo "缺少模版文件";exit;
    	}
    	$the_date = date('Y-m-d'); 
    	//查询用户
    	$customrers = Db::name('sms_customer')->select();
    	$success_mobile = "";
    	$fail_mobile = "";
    	foreach ($customrers as $customrer){
    	    // 将护照到期日转换为时间戳
    	    $expirationDateTimestamp = strtotime($customrer['passport_expiration_date']); 
    	    // 计算到期日前 180 天的日期
    	    $dateBefore180DaysTimestamp = strtotime("-180 day", $expirationDateTimestamp); 
    	    // 格式化输出为可读日期
    	    $customrer_month_day = date('Y-m-d', $dateBefore180DaysTimestamp); 
    		if($customrer_month_day == $the_date){
    			$mobile = $customrer['mobile'];
    			$name = $customrer['name']; 
    			$content ="【新天会展】". $config['value'];
    			$passport_expiration_date = $customrer['passport_expiration_date'];
    			$params = "$mobile,$name,$passport_expiration_date";
    			$result = self::sendSingleSms($content, $params);
    			if($result == true){
    			    $success_mobile .= $mobile.",";
    			}else{
    			    $fail_mobile .= $mobile.",";
    			} 
    		}
    	}
    	//这个给内部人员通知消息用
    	foreach ($mobiles as $mobile){
    	    $name = "福小新";
    	    $content ="【新天会展】". $config['value'];
    	    $dateAfter180Days = date('Y-m-d', strtotime("+180 day")); 
    	    $params = "$mobile,$name,$dateAfter180Days";
    	    $result = self::sendSingleSms($content, $params);
    	    if($result == true){
    	        $success_mobile .= $mobile.",";
    	    }else{
    	        $fail_mobile .= $mobile.",";
    	    }
    	}
    	//记录日志
    	$send_result = "护照到期 成功的手机号有：".$success_mobile."; 失败的手机号有： ".$fail_mobile;
    	$send_time = date('Y-m-d H:i:s');
    	$data = [
    	    'send_result' => $send_result,
    	    'send_time' => $send_time
    	];
    	Db::name('sms_log')->insert($data);
    	echo  date("Y-m-d") ." Today's passport processing has ended"; 
    }
    
    
    /*
    * 发送短信
    * @param unknown $mobile 手机号
    * @param unknown $content
    */
    public static function sendSingleSms($content, $params){
        $clapi  = new \ChuanglanSmsApi();   
        log_message('content值为:'.$content,'log',LOG_PATH . '../smslog/');  
        log_message('params值为:'.$params,'log',LOG_PATH . '../smslog/');  
        $result = $clapi->sendVariableSMS($content, $params); 
        log_message('请求短信商返回值为:'.$result,'log',LOG_PATH . '../smslog/');  
        if(!is_null(json_decode($result))){
            $output=json_decode($result,true);
            if(isset($output['code'])  && $output['code']=='0'){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        } 
    }
    
     /**
      * 发送短信
      * @param unknown $mobile 手机号
      * @param unknown $content
      */
    public static function sendSms(){
        $clapi  = new \ChuanglanSmsApi();
        $code = mt_rand(100000,999999);  
        
        
        $logs = Db::name('sms_log')->where('send_status','neq', 1)->select();
        
        foreach ($logs as $log){
        	$content = $log['send_content'];
        	$mobile = $log['mobile'];
        	$params = $log['send_params'];
        	$result = $clapi->sendVariableSMS($content, $params);
        	$id = $log['id'];
        	if(!is_null(json_decode($result))){
        		$output=json_decode($result,true);
        		if(isset($output['code'])  && $output['code']=='0'){
        			$update = [
        					'send_status' => 1,
        					'send_result' => $output['errorMsg'],
        					'send_time' => date("Y-m-d H:i:s")
        			];
        			Db::name('sms_log')->where('id', $id)->update($update);
        			echo "【发送成功】手机号:".$mobile.",发送内容：".$content. ",发送结果:".$output['errorMsg']."\r\n";
        		}else{
        			$update = [
        					'send_status' => 2,
        					'send_result' => $output['errorMsg'],
        					'send_time' => date("Y-m-d H:i:s")
        			];
        			Db::name('sms_log')->where('id', $id)->update($update);
        			echo "【发送失败】手机号:".$mobile.",发送内容：".$content.",发送结果:".$output['errorMsg']."\r\n";
        		}
        	}else{
        		$update = [
        				'send_status' => 2,
        				'send_result' => "请求失败",
        				'send_time' => date("Y-m-d H:i:s")
        		];
        		Db::name('sms_log')->where('id', $id)->update($update);
        		echo "【发送失败】手机号:".$mobile.",发送内容：".$content.",发送结果:".$output['errorMsg']."\r\n";
        	}
        }
         
    }
    /**
     * 查询有多少条数据
     */
    public static function queryBalance(){
        $clapi  = new \ChuanglanSmsApi();
        $result = $clapi->queryBalance();
        return $result;
    } 
    
}